﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.Composition;
using System.Windows.Data;
using System.Windows.Input;
using Caliburn.Micro;
using CardPlay.Client.Converters;
using CardPlay.Client.Model;

namespace CardPlay.Client.ViewModels
{
    [Export(typeof(GameHistoryViewModel)), PartCreationPolicy(CreationPolicy.NonShared)]
    public class GameHistoryViewModel : PropertyChangedBase
    {
        private readonly CollectionViewSource _history = new CollectionViewSource();
        private IEnumerable<RecordOfPlay> _source;

        public ICommand RetryGame { get; set; }

        public GameHistoryViewModel()
        {
            new GroupingAction<RecordOfPlay>("TimeStarted", String.Empty)
            {
                SortDirection = ListSortDirection.Descending,
                GenerateGroups = GroupByDate
            }.Apply(_history);
        }

        public object Data
        {
            get { return _history.View; }
        }

        public IEnumerable<RecordOfPlay> Source
        {
            get { return _source; }
            set
            {
                if (value == Source) return;

                _source = value;

                using (_history.DeferRefresh())
                    _history.Source = Source;

                NotifyOfPropertyChange(() => Data);
            }
        }

        private static object GroupByDate(RecordOfPlay play, Type arg2)
        {
            return play.TimeStarted.Date.ToString("D");
        }
    }
}
